<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2020/5/13
  Time: 10:11
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="commons/header.jsp" %>
<form class="form-inline" onsubmit="javascript: return false;">
    <div class="form-group">
        <label for="name">用户: </label>
        <input autocomplete="off" class="form-control" id="name">
    </div>
    <div class="form-group">
        <label for="titleMessage">标题: </label>
        <input autocomplete="off" class="form-control" id="titleMessage">
    </div>
    <div class="form-group">
        <label for="status">状态: </label>
        <select class="form-control" id="status">
            <option value="-1">全部</option>
            <option value="1">已发送</option>
            <option value="2">未发送</option>
        </select>
    </div>
    <div class="form-group">
        <label>创建日期: </label>
        <input class="form-control Wdate" style="height: 36px"
               onclick="WdatePicker({dateFmt:'yyyy-MM-dd',readOnly:true})" autocomplete="off"
               id="beginDate"> -
        <input autocomplete="off" style="height: 36px"
               onclick="WdatePicker({dateFmt:'yyyy-MM-dd',readOnly:true})" class="form-control Wdate"
               id="endDate">
    </div>
    <div class="form-group">
        <button class="btn btn-danger" onclick="querySearch()">搜索</button>
        <button autocomplete="off" class="btn btn-danger" onclick="resetSearch()">重置</button>
    </div>
</form>
<button id="remove" class="btn btn-danger">批量删除</button>
<button id="addMessage" class="btn btn-danger" onclick="addMessage()">添加</button>

<table id="goodsDataTable" class="table table-bordered table-striped"></table>

<div class="modal fade" id="addModal" data-backdrop="static" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
                <h4 class="modal-title">添加推送信息</h4>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <label>信息头</label>
                        <input class="form-control" id="addTitle" autocomplete="off">
                    </div>
                    <div id="wangEditor" class="text-align" tabindex="-1">
                        <p>欢迎使用 <b>极光推送</b></p>
                    </div>
                    <br>
                    <div class="form-group">
                        <span>推送对象</span> &nbsp;&nbsp;&nbsp;&nbsp;
                        <div class="radio">
                            <label>
                                <input type="radio" name="optionsRadios1" checked>
                                广播
                                &nbsp;&nbsp;&nbsp;&nbsp;
                                <input type="radio" name="optionsRadios1" id="userStatusClick" onclick="userClick()">
                                自定义用户:
                                <select id="userStatus" style="display: inline-block"></select>
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <span>推送时间</span> &nbsp;&nbsp;&nbsp;&nbsp;
                        <div class="radio">
                            <label>
                                <input type="radio" name="optionsRadios" id="optionsRadios1" checked>
                                立即发送
                            </label>
                            <label>
                                &nbsp;&nbsp;&nbsp;&nbsp;
                                <input type="radio" name="optionsRadios" id="optionsRadios2" value="1">
                                &nbsp;&nbsp;&nbsp;&nbsp;
                                自定义
                                <input class="form-control Wdate"
                                       style="height: 36px;width: 150px;display: inline-block;"
                                       onclick="WdatePicker({dateFmt:'yyyy-M-d H:mm:ss',minDate:'%y-%M-%d %H-%m-%s',readOnly:true})"
                                       autocomplete="off"
                                       id="MessageTime">

                            </label>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="addMessages()">确定</button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="showModal" data-backdrop="static" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
                <h4 class="modal-title">推送信息详情</h4>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <label>信息标题</label>
                        <input class="form-control" id="showTitle" readonly>
                    </div>
                    <textarea id="showWangEditor" cclass="form-control" rows="6" cols="60" readonly>
                    </textarea>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="showMessage()">确定</button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="editModal" data-backdrop="static" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">编辑</h4>
            </div>
            <div class="modal-body">
                <form>
                    <input type="hidden" id="editMessageId">
                    <div class="form-group">
                        <label>用户</label>
                        <input class="form-control" id="editName">
                    </div>
                    <div class="form-group">
                        <label>标题</label>
                        <input class="form-control" id="editTitle">
                    </div>
                    <div class="form-group">
                        <label>内容: </label>
                        <textarea class="form-control" id="editContent">
                        </textarea>
                    </div>
                    <div class="form-group">
                        <label>状态</label>
                        <select class="form-control" id="editStatus">
                            <option value="1">已发送</option>
                            <option value="2">未发送</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="editMessage()">保存</button>
            </div>
        </div>
    </div>
</div>

<script>


    function userClick() {
        var statusClick = $('#userStatus');
        if (document.getElementById('userStatusClick').checked) {
            $.getJSON('${pageContext.servletContext.contextPath}/message/getUser', {}, function (_data) {
                //遍历数组
                for (var i = 0; i < _data.length; i++) {
                    statusClick.append('<option value="' + _data[i].id + '">' + _data[i].name + '</option>')
                }
            })
        }
    }

    function showMessage() {
        $('#showModal').modal('hide');
    }

    function getContent(id) {
        $.ajax({
                url: '${pageContext.servletContext.contextPath}/message/showContent',
                type: 'post',
                data: {id: id},
                dataType: 'json',
                success: function (_data) {
                    if (_data) {
                        $('#showTitle').val(_data.title);
                        $('#showWangEditor').val(_data.content);
                        $('#addModal').modal("hide")
                        $('#goodsDataTable').bootstrapTable('refresh');
                    } else {
                        // showErrorBox('编辑失败')
                    }
                }
            }
        )
        $('#showModal').modal('show');
    }


    $('#goodsDataTable').bootstrapTable({
        url: '${pageContext.servletContext.contextPath}/message/getMessage',
        method: 'GET',
        columns: [
            {checkbox: true},
            {title: 'ID', field: 'id', align: 'center'},
            {title: '信息创建人', field: 'name', align: 'center'},
            {title: '信息标题', field: 'title', align: 'center'},
            {title: '信息内容', field: 'content',cellStyle:formatTableUnit, formatter :paramsMatter},
            {title: '创建时间', field: 'createTime', align: 'center', formatter: formatTime},
            {title: '发送时间', field: 'pushTime', align: 'center', formatter: formatTime},
            {title: '发送人群', field: 'userId', align: 'center', formatter: formatUserId},
            {title: '发送状态', field: 'status', align: 'center', formatter: formatStatus},
            {title: '操作', formatter: formatProcess, align: 'center'}
        ],
        sidePagination: 'server',
        pagination: true, //表示使用分页
        striped: true, // 设置为true会有隔行变色效果
        clickToSelect: true,//是否启用点击选中行
        toolbar: '#goodsTableToolbar', //设置工具条
        pageList: [10, 15, 20],
        queryParams: function (params) {
            var name = $('#name').val();
            var status = $('#status').val();
            var endDate = $('#endDate').val();
            var beginDate = $('#beginDate').val();
            var title = $('#titleMessage').val();
            //给js对象添加参数

            params.name = name;
            params.status = status;
            params.begin = beginDate;
            params.end = endDate;
            params.title = title;
            return params;
        }
    })

    //表格超出宽度鼠标悬停显示td内容
    function paramsMatter(value,row,index) {
        var span=document.createElement("span");
        span.setAttribute("title",value);
        span.innerHTML = value;
        return span.outerHTML;
    }
    //td宽度以及内容超过宽度隐藏
    function formatTableUnit(value, row, index) {
        return {
            css: {
                "white-space": "nowrap",
                "text-overflow": "ellipsis",
                "overflow": "hidden",
                "max-width":"150px"
            }
        }
    }

    // 格式化日期
    function formatTime(value) {
        return moment(value).format('YYYY-MM-DD HH:mm:ss')
    }

    // 格式化日期
    function formatUserId(value) {
        if (value > 0) {
            return '<span class="label label-purple">个人</span>'
        }
        return '<span class="label label-primary">广播</span>'
    }

    //富文本编辑框生成
    const E = window.wangEditor
    var editor = new E('#wangEditor')
    editor.create()

    function addMessage() {
        // var editorContent = document.getElementById('wangEditor')
        $('#addModal').modal('show');
    }

    function addMessages() {
        var text = document.getElementById('wangEditor').innerText;
        var textstr = text.replace(/<[^>]*>|/g, "")
        var addMessageTitle = $('#addTitle').val()

        var userStatus = -1
        if (document.getElementById('userStatusClick').checked) {
            userStatus = $('#userStatus').val()
        }
        if (document.getElementById('optionsRadios1').checked) {
            $.ajax({
                    url: '${pageContext.servletContext.contextPath}/message/sending',
                    type: 'post',
                    data: {content: textstr, addTitle: addMessageTitle, userStatus: userStatus},
                    dataType: 'json',
                    success: function (_data) {
                        if (_data.code > 0) {
                            $('#addModal').modal("hide")
                            $('#goodsDataTable').bootstrapTable('refresh');
                        } else {
                            // showErrorBox('编辑失败')
                        }
                    }
                }
            )
        } else {
            var messageTime = $('#MessageTime').val()
            $.ajax({
                url: '${pageContext.servletContext.contextPath}/message/sendDelay',
                type: 'post',
                data: {content: textstr, addTitle: addMessageTitle, messageTime: messageTime, userStatus: userStatus},
                dataType: 'json',
                success: function (_data) {
                    if (_data.code > 0) {
                        $('#addModal').modal("hide")
                        $('#goodsDataTable').bootstrapTable('refresh');
                    } else {
                        // showErrorBox('编辑失败')
                    }
                }
            })

        }
        $('#optionsRadios2').val('');
        $('#addModal').modal('hide');

    }

    // 获取选中删除按钮事件
    $("#remove").on("click", function () {
        if (!confirm("是否确认删除？"))
            return;
        var rows = $("#goodsDataTable").bootstrapTable('getSelections');// 获得要删除的数据
        if (rows.length == 0) {// rows 主要是为了判断是否选中，下面的else内容才是主要
            alert("请先选择要删除的记录!");
            return;
        } else {
            var ids = new Array();// 声明一个数组
            $(rows).each(function () {// 通过获得别选中的来进行遍历
                ids.push(this.id);// cid为获得到的整条数据中的一列
            });
            deleteMs(ids);

        }
    })

    //批量删除
    function deleteMs(ids) {
        $.ajax({
            url: '${pageContext.servletContext.contextPath}/message/deleteByDis',
            // contentType: "application/json",
            data: 'ids=' + ids,
            type: "post",
            dataType: "json",
            success: function (_data) {
                if (_data.code > 0) {
                    $('#goodsDataTable').bootstrapTable('refresh');
                } else {
                    alert("删除失败")
                }
            }
        });
    }

    //消息状态
    function formatStatus(value, rows) {
        if (value == 2) {
            return '<span class="label label-danger">未发送</span>'
        } else if (value == 1) {
            return '<span class="label label-default">已发送</span>'
        } else {
            return '<span class="label label-success">其他</span>'
        }
    }

    // 返回操作按钮
    function formatProcess(value, rows) {
        if (rows.status == 1) {
            return '<button onclick="getContent(' + rows.id + ')" class="btn btn-info btn-xs">查看详情</button>';
        }
        return '<button onclick="showEditUserModal(' + rows.id + ')" class="btn btn-danger btn-xs">编辑</button>' +
            '<button onclick="getContent(' + rows.id + ')" class="btn btn-info btn-xs">查看详情</button>';
    }

    // 查询用户信息，用于编辑的数据回显
    function showEditUserModal(messageId) {
        $('#editMessageId').val(messageId)
        $.ajax({
            url: '${pageContext.servletContext.contextPath}/message/getMessageById',
            type: 'get',
            data: {id: messageId},
            dataType: 'json',
            success: function (_data) {
                if (_data) {
                    $('#editName').val(_data.name)
                    $('#editTitle').val(_data.title)
                    $('#editStatus').val(_data.status)
                    $('#editContent').val(_data.content)

                } else {
                    alert('编辑失败');
                }
            }
        })
        $('#editModal').modal('show'); //展示编辑的模态框
    }

    //编辑用户
    function editMessage() {
        var editMessages = {};
        var messageId = $('#editMessageId').val();
        var name = $('#editName').val();
        var title = $('#editTitle').val();
        var status = $('#editStatus').val();
        var content = $('#editContent').val();
        //给js对象添加参数
        editMessages.id = messageId;
        editMessages.name = name;
        editMessages.title = title;
        editMessages.status = status;
        editMessages.content = content;
        $.ajax({
            url: '${pageContext.servletContext.contextPath}/message/putMessageById',
            type: 'post',
            contentType: "application/json",
            data: JSON.stringify(editMessages),
            dataType: 'json',
            success: function (_data) {
                if (_data.code > 0) {
                    $('#editModal').modal("hide")
                    $('#goodsDataTable').bootstrapTable('refresh');

                } else {
                    // showErrorBox('编辑失败')

                }
            }
        })
    }

    // 添加操作按钮
    function addProcessBtn(value, row) {
        return '<button onclick="getUserAddress(' + row.id + ')" class="btn btn-danger btn-xs">查看详情</button>'
    }

    //当内容长度大于30的时候，多余的不显示
    function formatTitle(value) {
        var length = value.length; //获取文本长度
        if (length > 30) {
            return value.substring(0, 31) + '...';
        }
        return value;
    }

    function resetSearch() {
        $('#name').val('');
        $('#status').val('-1');
        $('#endDate').val('');
        $('#beginDate').val('');
        $('#titleMessage').val('');
        $('#goodsDataTable').bootstrapTable('selectPage', 1);
    }

    // 点击搜索按钮的，执行搜素
    function querySearch() {
        // 跳转到表格的第一页
        $('#goodsDataTable').bootstrapTable('selectPage', 1);
    }
</script>
